#include "net_include.h"
#include "./wrap.h"
#include "./request_process.h"
#define PORT (9001)
#define MAX_SZIE (1024)
void fn(char *p);
int init_listen_socket(int port);
int main(int argc ,char **argv)
{
    int serversocket = 0;
    int maxi = -1;
    int ret = 0;
    int epfd = 0;
    if(argc != 3){
        printf("Usage: ./%s port dir\n",argv[0]);
        exit(EXIT_FAILURE);
    }
    ret = chdir(argv[2]);
    if(ret == -1){
        sys_error("chdir");
    }
    struct sockaddr_in client_addr;
    socklen_t socklen = sizeof(struct sockaddr_in);
    struct epoll_event eEvent[MAX_SZIE], tep;
    serversocket = init_listen_socket(atoi(argv[1]));
    epfd = epoll_create(1024);
    if (epfd == -1)
    {
        sys_error("epoll error");
    }
    tep.events = EPOLLIN;
    tep.data.fd = serversocket;
    epoll_ctl(epfd, EPOLL_CTL_ADD, serversocket, &tep);
    maxi = 0;
    for (;;)
    {
        ret = epoll_wait(epfd, eEvent, MAX_SZIE, -1);
        if (ret == -1){
            sys_error("epoll error");
        }
        else if (ret > 0){
            for (size_t i = 0; i < ret; i++)
            {
                if (eEvent[i].data.fd == serversocket){
                    int fd = Accept(serversocket, (struct sockaddr *)&client_addr, &socklen);
                    char buf[100];
                    CLEAR_ARRAY(buf);
                    printf("New connection from IP:%s,port:%d\n", inet_ntop(AF_INET, &(client_addr.sin_addr), buf, sizeof(buf)),
                           ntohs(client_addr.sin_port));
                    // 设置 cfd 非阻塞
                    /*
                    int flag = fcntl(fd, F_GETFL);
                    flag |= O_NONBLOCK;
                    fcntl(fd, F_SETFL, flag);
                    */
                    tep.data.fd = fd;
                    tep.events = EPOLLIN|EPOLLET;
                    epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &tep);
                }
                else{
                    process_accept(eEvent[i].data.fd,epfd);
                }
            }
        }
    }
}
void fn(char *p)
{
    if (!p){
        return;
    }
    while (*p){
        *p = toupper(*p);
        p++;
    }
}
socket_t init_listen_socket(int port)
{
    struct sockaddr_in addr ;
    memset(&addr, 0, sizeof(addr));
    socket_t serversocket = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    Bind(serversocket, (struct sockaddr *)&addr, sizeof(addr));
    Listen(serversocket, 10);
    return serversocket;
}




static void os_socket_init(void)
{

}